<template>
  <div class="main ad-manage-list">
    <section>
      <el-form
        ref="searchForm"
        class="search-block"
        :model="listQuery"
        label-position="left"
        label-width="82px"
      >
        <el-row :gutter="50">
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item label="开播时间：">
              <el-date-picker
                v-model="listQuery.searchDate"
                type="daterange"
                range-separator="~"
                value-format="yyyy-MM-dd"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="medium"
              ></el-date-picker>
              <el-button type="primary" size="mini" plain @click="changeDateTime(0)">今天</el-button>
              <el-button type="primary" size="mini" plain @click="changeDateTime(1)">昨天</el-button>
              <el-button type="primary" size="mini" plain @click="changeDateTime(2)">近七天</el-button>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item label="直播标题：" label-width="100px" prop="liveTitle">
              <el-input v-model="listQuery.liveTitle" placeholder="直播标题" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item label="直播状态：" prop="liveStatus">
              <el-select v-model="listQuery.liveStatus" placeholder="请选择" size="medium" filterable>
                <el-option
                  v-for="item in liveStatus"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item label="主播手机号：" label-width="100px" prop="mobile">
              <el-input v-model="listQuery.mobile" placeholder="按照手机号搜索" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item label="直播标签：" prop="liveTags">
              <el-select v-model="listQuery.liveTags" placeholder="请选择" size="medium" filterable>
                <el-option value="" label="全部"></el-option>
                <el-option value="美妆" label="美妆"></el-option>
                <el-option value="母婴" label="母婴"></el-option>
                <el-option value="美食" label="美食"></el-option>
                <el-option value="健康" label="健康"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label class="btn-item">
          <el-button type="primary" size="mini" icon="el-icon-search" plain @click="search">搜索</el-button>
          <span class="btn-reset" @click="resetForm('searchForm')">清空搜索条件</span>
        </el-form-item>
      </el-form>
      <el-table
        :data="list"
        v-loading="listLoading"
        element-loading-text="给我一点时间"
        border
        highlight-current-row
      >
        <el-table-column type="index" width="50" label="序号"></el-table-column>
        <el-table-column align="center" label="直播ID" prop="liveId"></el-table-column>
        <el-table-column align="center" label="直播标题" prop="liveTitle"></el-table-column>
        <el-table-column align="center" label="开播时间" prop="beginDate"></el-table-column>
        <el-table-column align="center" label="当前直播时长" prop="liveDuration"></el-table-column>
        <el-table-column align="center" label="状态" prop="liveStatus">
          <template slot-scope="scope">{{scope.row.liveStatus | liveType}}</template>
        </el-table-column>
        <el-table-column align="center" label="直播标签" prop="liveTags" width="160"></el-table-column>
        <el-table-column align="center" label="主播昵称" prop="nickname" width="160"></el-table-column>
        <el-table-column align="center" label="主播手机号" width="160" prop="mobile"></el-table-column>
        <el-table-column align="center" label="直播间隐藏标识">
          <template slot-scope="scope">
             {{ scope.row.showApp === 1 ? '公开': '隐藏'}}
          </template>
        </el-table-column>
          <el-table-column align="center" label="抽奖次数" width="80" prop="luckDrawCnt"></el-table-column>
        <el-table-column align="left" label="操作" width="380" v-if="JSON.stringify(rightsButtons) !== '{}'">
          <template slot-scope="scope">
            <el-button
              v-if="rightsButtons['operate'] && scope.row.liveStatus === 1"
              type="info"
              size="mini"
              @click="showReviewLive(scope.row)"
              plain
            >审核</el-button>

            <el-button
              v-if="rightsButtons['refuseReason'] && scope.row.liveStatus === 8"
              @click="showRejectDialg(scope.row)"
              type="warning"
              size="mini"
              plain
            >拒绝原因</el-button>
            <el-button v-if="rightsButtons['detail']" type="primary" size="mini" plain @click="showLiveDetail(scope.row)">查看直播信息</el-button>
            <el-button
              type="danger"
              v-if="rightsButtons['end'] && scope.row.liveStatus === 3"
              size="mini"
              plain
              @click="showCloseReason(scope.row,true)"
            >关闭直播间</el-button>
            <el-button
              type="danger"
              v-if="rightsButtons['endReason'] && scope.row.liveStatus === 6"
              size="mini"
              plain
              @click="showCloseReason(scope.row,false)"
            >关闭原因</el-button>
            <el-button
              v-if="rightsButtons['report'] && scope.row.liveStatus === 5"
              type="primary"
              size="mini"
              plain
              @click="showLiveData(scope.row)"
            >查看报表</el-button>

            <el-button v-if="rightsButtons['delete']" @click="showDeleteConfirm(scope.row)" type="danger" size="mini" plain>删除</el-button>
            <el-button v-if="rightsButtons['setShowStatus']"  @click="handleRoomConfirm(scope.row)" size="mini"  type="info" plain>
              {{ scope.row.showApp === 1 ? '设为隐藏直播间': '设为显示直播间'}}
            </el-button>
            <el-button v-if="rightsButtons['lookResult']" type="primary" size="mini" plain @click="handleLuckResult(scope.row)">抽奖结果</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="listQuery.pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="listQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="listTotal"
      ></el-pagination>
    </section>
    <el-dialog title="审核" :visible.sync="examineDialog" width="30%">
      <el-radio v-model="examineStatus" :label="1">审核通过</el-radio>
      <el-radio v-model="examineStatus" :label="0">审核拒绝</el-radio>
      <el-input
        style="margin-top:20px"
        placeholder="拒绝原因"
        :disabled="examineStatus === 1"
        v-model="examineReason"
        type="textarea"
        :rows="4"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetParams">取 消</el-button>
        <el-button type="primary" @click="setLiveReview">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="关闭原因" @close='resetParams'  :visible.sync="closeReasonDialog" width="30%">
      <el-input
        v-if="closeEdit"
        placeholder="请填写关闭的原因"
        v-model="closeReason"
        type="textarea"
        :rows="4"
      />
      <span v-else>{{ closeReason }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="closeEdit" @click="resetParams">取 消</el-button>
        <el-button type="primary" @click="colseLive">{{ closeEdit ? '确 定' : '我知道了' }}</el-button>
      </span>
    </el-dialog>
    <el-dialog title="拒绝原因" :visible.sync="refuseDialg" width="30%">
      <span>{{ closeReason }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="resetParams">我知道了</el-button>
      </span>
    </el-dialog>
    <el-dialog title="直播详情" :visible.sync="liveDetailDialog" width="40%">
      <div class="live_detail_content">
        <div class="live_item">
          <span>直播标题：</span>
          <span>{{liveMsg.liveTitle}}</span>
        </div>
        <div class="live_item">
          <span>直播封面：</span>
          <img class="live_img" :src="liveMsg.coverImg" />
        </div>
        <div class="live_item">
          <span>开播时间：</span>
          <span>{{liveMsg.beginDate}}</span>
        </div>
        <div class="live_item">
          <span>结束时间：</span>
          <span>{{liveMsg.realEndDate}}</span>
        </div>
        <div class="live_item">
          <span>本场主播：</span>
          <span>{{liveMsg.nickname}}</span>
        </div>
        <div class="live_item">
          <span>直播商品：</span>
          <div class="liveGoods">
            <div v-for="good in liveMsg.goodsList" :key="good.goodsId">
              <div class="live_item">
                <span class="txt">商品编号</span>
                <span class="txt">商品名称</span>
              </div>
              <div class="live_item">
                <el-tooltip effect="dark" :content="good.goodsId" placement="top">
                  <span class="txt">{{good.goodsId}}</span>
                </el-tooltip>
                <el-tooltip effect="dark" :content="good.goodsName" placement="top">
                  <span class="txt">{{good.goodsName}}</span>
                </el-tooltip>
              </div>
            </div>
          </div>
        </div>
        <div class="live_item">
          <span>直播助理：</span>
          <div>
            <div v-for="(ass,idx) in liveMsg.assistantList" :key="idx" class="live_item">
              <span>{{ass.assistantName}} -- </span>
              <span>{{ass.assistantMobile}}</span>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="resetParams">关闭</el-button>
      </span>
    </el-dialog>
    <live-data :visible.sync="liveDataDialog" :data="liveData" />
  </div>
</template>

<script>
import moment from 'moment'
import LiveData from '../components/LiveData'
import {
  getLiveNoticeList,
  setLiveReviewPass,
  setLiveReviewReject,
  getLiveDetail,
  setForbiddenLive,
  getLiveData,
  deletLive,
  setStopLive,
  setShowApp
} from '@/api/bizhibo'
export default {
  name: 'bzb-livelist',
  components: {
    LiveData
  },
  filters: {
    liveType(val) {
      const type = {
        1: '待审核',
        2: '待开始',
        3: '直播中',
        4: '暂停',
        5: '正常结束',
        6: '被禁用',
        7: '超时作废',
        8: '审核拒绝',
        9: '时间结束,强制关闭'
      }
      return type[val]
    }
  },
  data() {
    return {
      closeReason: '',
      closeEdit: false, //
      currentData: '', //当前操作数据
      examineReason: '',
      examineStatus: 1,
      examineDialog: false,
      liveDataDialog: false, //直播数据弹窗
      closeReasonDialog: false,
      deletePopVisible: false,
      liveDetailDialog: false,
      refuseDialg: false,
      liveMsg: {}, //直播间信息
      liveData: {},
      list: [{ id: '1' }],
      listLoading: false,
      listTotal: 0,
      listQuery: {
        liveTitle: '',
        liveStatus: '',
        searchDate: [],
        liveBeginDate: '',
        liveEndDate: '',
        mobile: '',
        title: '',
        liveTags: '',
        pageNo: 1,
        pageSize: 10
      },
      liveStatus: [
        {
          label: '全部',
          value: ''
        },
        {
          label: '待审核',
          value: 1
        },
        {
          label: '待直播',
          value: 2
        },
        {
          label: '直播中',
          value: 3
        },
        // {
        //   label: '暂停中',
        //   value: 4
        // },
        {
          label: '直播结束',
          value: 5
        },
        {
          label: '违规下线',
          value: 6
        },
        {
          label: '超时作废',
          value: 7
        },
        {
          label: '时间结束，强制关闭',
          value: 9
        }
      ]
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      try {
        const query = {
          ...this.listQuery,
          searchDate: this.listQuery.search && [...this.listQuery.searchDate]
        }
        delete query.searchDate
        const { data } = await getLiveNoticeList(query)
        this.list = data.records
        this.listTotal = data.total
      } catch (error) {
        console.log(error)
      }
    },
    search() {
      if (this.listQuery.searchDate && this.listQuery.searchDate.length > 1) {
        this.listQuery.liveBeginDate = this.listQuery.searchDate[0]
        this.listQuery.liveEndDate = this.listQuery.searchDate[1]
      } else {
        this.listQuery.liveBeginDate = ''
        this.listQuery.liveEndDate = ''
      }
      this.listQuery.pageNo = 1
      this.getList()
    },
    // 直播间详情
    async showLiveDetail(val) {
      this.currentData = val
      this.liveDetailDialog = true
      try {
        const { data } = await getLiveDetail(this.currentData.liveId)
        this.liveMsg = data
        console.log('直播i', data)
      } catch (error) {
        console.log(error)
        this.$message.error('获取直播间数据失败')
      }
    },
    // 删除直播间二次确认
    async showDeleteConfirm(val) {
      this.currentData = val
      try {
        await this.$confirm(
          '是否确认删除此直播间？删除后，主播将失去此次直播记录。',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        this._deleteLive()
      } catch (error) {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
    },
    // 设置为隐藏直播间
    handleRoomConfirm(row) {
      const showApp = row.showApp === 1 ? 2 : 1  // 1都显示 2都不显
      const txt = row.showApp === 1 ? '是否确认隐藏该房间': '是否确认显示该房间'
      this.$confirm(txt, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        setShowApp({
          roundId: row.liveId,
          showApp: showApp
        }).then(res => {
          this.$message.success("设置成功")
            this.getList()
        }).catch(err => {
          console.log(err)
        })
      }).catch((err)=>{console.log(err)})
    },
    // 查看抽奖结果
    handleLuckResult(row) {
      console.log(row)
      this.$router.push({path: '/bizhibo/liveluck/'+row.liveId})
    },
    async _deleteLive() {
      try {
        const data = await deletLive(this.currentData.liveId)
        if (data.msg === 'SUCCESS') {
          this.$message.success('操作成功')
          this.getList()
        } else {
          this.$message.error('操作失败')
        }
        this.resetParams()
      } catch (error) {
        console.log(error)
        this.$message.error('操作失败')
      }
    },
    // 展示关闭弹窗
    showCloseReason(val, status) {
      if (!status) {
        this.closeReason = val.reason
      }
      this.closeReasonDialog = true
      this.closeEdit = status
      this.currentData = val
    },
    async showLiveData(val) {
      try {
        this.currentData = val
        this.liveDataDialog = true
        const { data } = await getLiveData(this.currentData.liveId)
        this.liveData = data
      } catch (error) {
        this.$message.error('获取直播数据失败')
      }
    },
    showRejectDialg(val) {
      this.refuseDialg = true
      this.closeReason = val.reason
    },
    showReviewLive(val) {
      this.examineDialog = true
      this.currentData = val
    },
    // 清空搜索条件
    resetForm(formName) {
      this.$nextTick(() => {
        this.listQuery.searchDate = []
        this.$refs[formName].resetFields()
      })
    },
    // 审核直播间
    async setLiveReview() {
      try {
        let data = null
        // examineStatus 1 审核通过
        if (this.examineStatus === 1) {
          data = await setLiveReviewPass(this.currentData.liveId, {
            reason: ''
          })
        } else {
          if (!this.examineReason) {
            this.$message.error('请填写拒绝原因')
            return
          }
          data = await setLiveReviewReject(this.currentData.liveId, {
            reason: this.examineReason
          })
        }

        if (data.msg === 'SUCCESS') {
          this.$message.success('操作成功')
          this.getList()
        } else {
          this.$message.error('操作失败')
        }
        this.resetParams()
      } catch (error) {
        console.log(error)
        this.$message.error('操作失败')
      }
    },
    // 关闭直播间
    async colseLive() {
      if (!this.closeEdit) {
        return this.resetParams()
      }
      try {
        if (!this.closeReason) {
          this.$message.error('请填写关闭原因')
          return
        }
        const data = await setForbiddenLive(this.currentData.liveId, {
          reason: this.closeReason
        })
        if (data.msg === 'SUCCESS') {
          this.$message.success('操作成功')
          this.getList()
        }
        this.resetParams()
      } catch (error) {
        console.log(error)
        this.$message.error('操作失败')
      }
    },
    // 参数重置
    resetParams() {
      this.closeReason = ''
      this.currentData = ''
      this.examineReason = ''
      this.examineStatus = 1
      this.examineDialog = false
      this.liveDataDialog = false
      this.closeReasonDialog = false
      this.deletePopVisible = false
      this.liveDetailDialog = false
      this.refuseDialg = false
      this.closeEdit = false
    },
    // 切换分页
    handleCurrentChange(page) {
      this.listQuery.pageNo = page
      this.getList()
    },
    // 切换分页数
    handleSizeChange(pageSize) {
      this.listQuery.pageSize = pageSize
      this.getList()
    },

    //时间修改选择
    changeDateTime(type) {
      const date = []
      //今天
      if (type === 0) {
        date[0] = moment().format('YYYY-MM-DD')
        date[1] = moment().format('YYYY-MM-DD')
      } else if (type === 1) {
        //昨天
        date[0] = moment()
          .subtract(1, 'day')
          .format('YYYY-MM-DD')
        date[1] = moment()
          .subtract(1, 'day')
          .format('YYYY-MM-DD')
      } else {
        //近七天
        date[0] = moment()
          .subtract(7, 'day')
          .format('YYYY-MM-DD')
        date[1] = moment()
          .subtract(1, 'day')
          .format('YYYY-MM-DD')
      }
      this.listQuery.searchDate = date
    }
  }
}
</script>
<style lang="scss" scoped>
.live_detail_content {
  font-size: 16px;
  color: #333;
  max-height: 600px;
  overflow-y: auto;
  .live_img {
    max-width: 100%;
    height: 100px;
  }
  .liveGoods {
    display: flex;
    flex-direction: column;
  }
  .live_item {
    display: flex;
    margin-bottom: 30px;
    .txt {
      width: 200px;
      display: inline-block;
      margin-right: 20px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}
</style>
